package com.heo.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.heo.web.entity.Device;
import com.heo.web.service.HttpnDeviceService;
import com.heo.web.util.GsonUtils;
import com.heo.web.util.Utils;

/**
 * 嵌入式命令服务类
 */
@Controller
@RequestMapping("/d")
public class HttpnController {

	private static final Logger logger = Logger.getLogger(HttpnController.class);

	@Autowired
	private HttpnDeviceService httpnDeviceService;

	@RequestMapping("/n")
	public void requestEwash(Model model, HttpServletRequest req,
			HttpServletResponse resp) {
		String m = null;
		try {
			String jsonString = req.getParameter("args");
			resp.setHeader("Date", "");
			resp.setHeader("Server", "");
			// 参数为空不返回
			if ("".equals(jsonString) || jsonString == null) {
				responseOutWithJson(resp, "args参数错误", m);
				return;
			}
			logger.info(jsonString);
			Device reqJson = (Device) GsonUtils.jsonToObject(jsonString,
					Device.class);
			// mac地址为空不返回
			if (!Utils.checkNull(reqJson.getM())) {
				responseOutWithJson(resp, "参数错误", m);
				return;
			}

			// s为空不返回
			if (!Utils.checkNull(reqJson.getS())) {
				responseOutWithJson(resp, "参数错误", m);
				return;
			}
			m = reqJson.getM();
			Map<String, Object> rspJson = httpnDeviceService
					.deviceController(reqJson);
//			System.out.println(ServletUtil.getRemoteHost(req) + "----------" + m);
			responseOutWithJson(resp, rspJson, m);
		} catch (Exception e) {
			System.out.println(e.toString());
			Map<String, Object> rspJson = new HashMap<String, Object>();
			rspJson.put("c", -2);
			rspJson.put("t", 120);
			rspJson.put("m", m);
			// rspJson.put("s", "218.16.123.124");
			rspJson.put("p", "9999");
			rspJson.put("u", "/d/n");
			rspJson.put("i", 150);
			responseOutWithJson(resp, rspJson, m);
		}
	}

	/**
	 * @param response
	 */
	protected void responseOutWithJson(HttpServletResponse response,
			Object reqJson, String macAddress) {

		String jsonString = GsonUtils.objectToJson(reqJson);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(jsonString);
			logger.info("macAddress=" + macAddress + "jsonString = " + jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
